package com.esgov.chatbot.dify;

import com.esgov.chatbot.config.DifyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Dify客户端
 */
@Component
public class DifyClient {

    @Autowired
    private DifyConfig difyConfig;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发送消息到Dify API (完整参数版本)
     *
     * @param query 用户问题
     * @param conversationId 会话ID（可选）
     * @param user 用户标识
     * @param responseMode 响应模式 (streaming 或 blocking)
     * @param inputs 输入参数
     * @return Dify响应
     */
    public DifyResponse sendMessage(String query, String conversationId, String user, String responseMode, Map<String, Object> inputs) {
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + difyConfig.getApiKey());

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("query", query);
        requestBody.put("user", user);
        requestBody.put("inputs", inputs != null ? inputs : new HashMap<>());
        
        if (conversationId != null && !conversationId.isEmpty()) {
            requestBody.put("conversation_id", conversationId);
        }
        
        requestBody.put("response_mode", responseMode != null ? responseMode : "blocking");

        // 创建HttpEntity
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        ResponseEntity<DifyResponse> response = restTemplate.exchange(
                difyConfig.getApiUrl() + "/chat-messages",
                HttpMethod.POST,
                entity,
                DifyResponse.class
        );

        return response.getBody();
    }
    
    /**
     * 发送消息到Dify API (简化版本)
     *
     * @param query 用户问题
     * @param conversationId 会话ID（可选）
     * @param user 用户标识
     * @return Dify响应
     */
    public DifyResponse sendMessage(String query, String conversationId, String user) {
        return sendMessage(query, conversationId, user, "blocking", null);
    }
}